package com.easylinkin.linkappapi.lobar.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.easylinkin.linkappapi.common.exceptions.BusinessException;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.lobar.dto.UserBlacklistDTO;
import com.easylinkin.linkappapi.lobar.dto.UserProjectDTO;
import com.easylinkin.linkappapi.lobar.entity.UserBlacklist;
import com.easylinkin.linkappapi.lobar.entity.UserBlacklistRecord;
import com.easylinkin.linkappapi.lobar.entity.UserProject;
import com.easylinkin.linkappapi.lobar.entity.emp.EmpUserBase;
import com.easylinkin.linkappapi.lobar.mapper.EmpUserBaseMapper;
import com.easylinkin.linkappapi.lobar.mapper.UserBlacklistMapper;
import com.easylinkin.linkappapi.lobar.mapper.UserBlacklistRecordMapper;
import com.easylinkin.linkappapi.lobar.service.UserBlacklistRecordService;
import com.easylinkin.linkappapi.lobar.service.UserBlacklistService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easylinkin.linkappapi.lobar.service.UserProjectService;
import com.easylinkin.linkappapi.operatelog.LogHelper;
import com.easylinkin.linkappapi.operatelog.constant.LogConstant;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;

import java.util.*;
import java.util.stream.Collectors;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 花名册黑名单表 服务实现类
 * </p>
 *
 * @author TongJie
 * @since 2022-04-13
 */
@Service
public class UserBlacklistServiceImpl extends ServiceImpl<UserBlacklistMapper, UserBlacklist> implements UserBlacklistService {

  @Resource
  private LinkappUserContextProducer linkappUserContextProducer;
  @Autowired
  private UserBlacklistRecordService userBlacklistRecordService;
  @Autowired
  private UserProjectService userProjectService;
  @Autowired
  private EmpUserBaseMapper empUserBaseMapper;
  @Autowired
  private UserBlacklistRecordMapper userBlacklistRecordMapper;

  /**
   * 增加
   * @param userBlacklist
   * @return
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public Map<String, Object> insert(UserBlacklist userBlacklist) {
    //记录日志
    if(userBlacklist != null){
      //修改之后，不会直接传递userId,而是通过身份证号进行处理
      fillUserId(userBlacklist);
      if (!Integer.valueOf(2).equals(userBlacklist.getEnterpriseSourceType())){
        //如果是项目端，状态为待审核
        userBlacklist.setApprovalStatus(0);
        //项目端日志
        EmpUserBase empUserBase = empUserBaseMapper.selectById(userBlacklist.getUserId());
        if(empUserBase != null){
          LogHelper.setContent(LogConstant.LogOperateType.LABOL_USER_ROSTER_ADD_BLACK,empUserBase.getName(),empUserBase.getCard());
        }
      }else {
        //企业端，状态为已审核
        userBlacklist.setApprovalStatus(1);
      }
    }
    /**
     * 验证重复
     */
    this.checkExist(userBlacklist);
    //设置基本属性
    this.setBase(userBlacklist);
    //删除掉以前审批被拒绝的黑名单信息
    baseMapper.delete(new QueryWrapper<UserBlacklist>().eq("user_id_",userBlacklist.getUserId()).eq("approval_status_",2));

    //下放指令
    this.save(userBlacklist);
    //添加加入黑名单记录
    UserBlacklistRecord userBlacklistRecord = new UserBlacklistRecord();
    userBlacklistRecord.setTenantId(userBlacklist.getTenantId());
    userBlacklistRecord.setUserId(userBlacklist.getUserId());
    userBlacklistRecord.setReason(userBlacklist.getReason());
    userBlacklistRecord.setType(1);
    if (Integer.valueOf(2).equals(userBlacklist.getEnterpriseSourceType())){
      //查询最新的人员在岗信息,这个用户可能不存在任何项目中,企业端不处理项目信息
//      UserProject userProject = userProjectService.findNew(userBlacklist.getUserId());
//      if (null != userProject){
//        userBlacklistRecord.setTenantId(userProject.getTenantId());
//      }
      userBlacklistRecord.setType(4);//企业级添加不需要审批
      userBlacklistRecord.setEnterpriseSourceType(2);
      userBlacklistRecord.setEnterpriseCreateUserId(userBlacklist.getEnterpriseCreateUserId());
      userBlacklistRecord.setEnterpriseCreateUserName(userBlacklist.getEnterpriseCreateUserName());
      userBlacklistRecord.setEnterpriseOrganizationId(userBlacklist.getEnterpriseOrganizationId());
    }
    userBlacklistRecordService.insert(userBlacklistRecord);
    //下放指令，如果是审核状态已通过，则直接进行下发,考虑几百面板机性能问题，暂不下发
//    if (Integer.valueOf(1).equals(userBlacklist.getApprovalStatus())){
//      EmpUserBase empUserBase = empUserBaseMapper.selectById(userBlacklist.getUserId());
//      Map<String, Object> map = userProjectService.userToGate(empUserBase, 2);
//      return map;
//    }
//    if (!Integer.valueOf(2).equals(userBlacklist.getEnterpriseSourceType())){
//      EmpUserBase empUserBase = empUserBaseMapper.selectById(userBlacklist.getUserId());
//      Map<String, Object> map = userProjectService.userToGate(empUserBase, 2);
//      return map;
//    }
    return null;
  }

  /**
   * 根据id编辑
   * @param userBlacklist
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void updateOne(UserBlacklist userBlacklist) {
    fillUserId(userBlacklist);
    /**
     * 验证重复
     */
    this.checkExist(userBlacklist);
    //设置基本属性
    this.setBase(userBlacklist);
    this.updateById(userBlacklist);
  }

  /**
   * 填充userId属性
   * @param userBlacklist
   */
  private void fillUserId(UserBlacklist userBlacklist) {
    //修改之后，不会直接传递userId,而是通过身份证号进行处理
    QueryWrapper<EmpUserBase> queryWrapper = new QueryWrapper<>();
    //判断重复条件
    queryWrapper.eq("card_", userBlacklist.getBaseUser().getCard());
    List<EmpUserBase> empUserBases = empUserBaseMapper.selectList(queryWrapper);
    if (empUserBases.size() > 0) {
      userBlacklist.setUserId(empUserBases.get(0).getId());
    }else {
      if (null == userBlacklist.getBaseUser()){
        throw new BusinessException("请先完善用户信息");
      }
      if (null == userBlacklist.getBaseUser().getUserProject()){
        userBlacklist.getBaseUser().setUserProject(new UserProjectDTO());
      }
      EmpUserBase empUserBase = userProjectService.saveEmpBaseUser(userBlacklist.getBaseUser());
     userBlacklist.setUserId(empUserBase.getId());
    }
  }

  /**
   * @Description: 移出黑名单
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   * @return
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public Map<String, Object> delOne(UserBlacklist userBlacklist, int type) {
    UserBlacklist blacklist = baseMapper.selectById(userBlacklist.getId());
    //记录操作记录
    //添加加入黑名单记录
    UserBlacklistRecord userBlacklistRecord = new UserBlacklistRecord();
    userBlacklistRecord.setUserId(blacklist.getUserId());
    userBlacklistRecord.setReason(userBlacklist.getReason());
    userBlacklistRecord.setType(type);
    //1.移出之前是哪个级别添加进来的
    if (Integer.valueOf(2).equals(blacklist.getEnterpriseSourceType())){
      userBlacklistRecord.setSrcOrganizationId(blacklist.getEnterpriseOrganizationId());
    }else {
      userBlacklistRecord.setSrcTenantId(blacklist.getTenantId());
    }
    //2.哪个级别移出的
    if (Integer.valueOf(2).equals(userBlacklist.getEnterpriseSourceType())){
      //查询最新的人员在岗信息，企业级添加，暂时不处理项目信息
//      UserProject userProject = userProjectService.findNew(blacklist.getUserId());
//      //有可能这个黑名单找不到相关的项目
//      if (null != userProject){
//        userBlacklistRecord.setTenantId(userProject.getTenantId());
//      }
      userBlacklistRecord.setEnterpriseSourceType(2);
      userBlacklistRecord.setEnterpriseCreateUserId(userBlacklist.getEnterpriseCreateUserId());
      userBlacklistRecord.setEnterpriseCreateUserName(userBlacklist.getEnterpriseCreateUserName());
      userBlacklistRecord.setEnterpriseOrganizationId(userBlacklist.getEnterpriseOrganizationId());
    }
    userBlacklistRecordService.insert(userBlacklistRecord);
    baseMapper.deleteById(userBlacklist.getId());
    //下发指令给闸机,考虑几百面板机性能问题，暂不下发
//    if (!Integer.valueOf(2).equals(userBlacklist.getEnterpriseSourceType())){
//      EmpUserBase empUserBase = empUserBaseMapper.selectById(blacklist.getUserId());
//      Map<String, Object> map = userProjectService.userToGate(empUserBase, 1);
//      return map;
//    }
    return null;
  }

  /**
   * @Description: 删除黑名单列表(企业级操作)
   * @author kan yuanfeng
   * @date 2020/11/04 11:42
   */
  @Override
  public void delBatch(UserBlacklist userBlacklist) {
    //查询涉及到的用户
    List<UserBlacklist> blacklists = baseMapper.selectBatchIds(userBlacklist.getIds());
    Set<String> userIds = blacklists.stream().map(b -> b.getUserId()).collect(Collectors.toSet());
    UpdateWrapper<UserBlacklistRecord> queryWrapper = new UpdateWrapper<>();
    queryWrapper.in("user_id_",userIds).set("show_",2);
    //添加操作记录
    userBlacklist.getIds().forEach(id ->{
      UserBlacklist blacklist = BeanUtil.toBean(userBlacklist, UserBlacklist.class);
      blacklist.setId(id);
      blacklist.setEnterpriseSourceType(2);
      this.delOne(blacklist,3);
    });
    userBlacklistRecordMapper.update(null,queryWrapper);
//    baseMapper.deleteBatchIds(userBlacklist.getIds());
  }

  /**
   * 审批黑名单，企业级操作
   * @param userBlacklist
   * @return
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public Map<String, Object> approve(UserBlacklist userBlacklist) {
    UserBlacklist blacklist = baseMapper.selectById(userBlacklist.getId());
    //记录操作记录
    //添加加入黑名单记录
    UserBlacklistRecord userBlacklistRecord = new UserBlacklistRecord();
    userBlacklistRecord.setUserId(blacklist.getUserId());
    if (userBlacklist.getApprovalStatus()== 1){
      userBlacklistRecord.setReason("审批通过： "+ userBlacklist.getReason());
    }else{
      userBlacklistRecord.setReason("审批拒绝： "+userBlacklist.getReason());
    }
    userBlacklistRecord.setType(5);
    //2.哪个级别移出的
    if (Integer.valueOf(2).equals(userBlacklist.getEnterpriseSourceType())){
      //查询最新的人员在岗信息
      UserProject userProject = userProjectService.findNew(blacklist.getUserId());
      //有可能这个黑名单找不到相关的项目
      if (null != userProject){
        userBlacklistRecord.setTenantId(userProject.getTenantId());
      }
      userBlacklistRecord.setEnterpriseSourceType(2);
      userBlacklistRecord.setEnterpriseCreateUserId(userBlacklist.getEnterpriseCreateUserId());
      userBlacklistRecord.setEnterpriseCreateUserName(userBlacklist.getEnterpriseCreateUserName());
      userBlacklistRecord.setEnterpriseOrganizationId(userBlacklist.getEnterpriseOrganizationId());
    }
    userBlacklistRecordService.insert(userBlacklistRecord);
    blacklist.setApprovalStatus(userBlacklist.getApprovalStatus());
    baseMapper.updateById(blacklist);
    //下发指令给闸机,如果是通过，则下发至闸机，考虑几百面板机下发性能问题，暂不下发
//    EmpUserBase empUserBase = empUserBaseMapper.selectById(blacklist.getUserId());
//    Map<String, Object> map = userProjectService.userToGate(empUserBase, 1);
    return null;
  }

  @Override
  public IPage<UserBlacklistDTO> queryListByPage(RequestModel<UserBlacklistDTO> requestModel) {
    Page page = requestModel.getPage();
    UserBlacklist userBlacklist = requestModel.getCustomQueryParams();
    //项目id 过滤
    if (null != linkappUserContextProducer.getCurrent()){
      userBlacklist.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
    }
    IPage<UserBlacklistDTO> userBlacklistIPage = baseMapper.queryListByPage(page, userBlacklist);
    return userBlacklistIPage;
  }

  /**
   * 验证重复
   */
  private void checkExist(UserBlacklist userBlacklist) {
    QueryWrapper<UserBlacklist> queryWrapper = new QueryWrapper<>();
    //设置判断重复条件
    //黑名单全局共享，去掉项目限制
//    if (null != linkappUserContextProducer.getCurrent()){
//      queryWrapper.eq("tenant_id_",linkappUserContextProducer.getNotNullCurrent().getTenantId());
//    }
    queryWrapper.eq("user_id_",userBlacklist.getUserId());
    //编辑的时候存在id
    Optional.ofNullable(userBlacklist.getId()).ifPresent(id -> queryWrapper.ne("id",userBlacklist.getId()));
    //查下出待审查以及审查通过的
    queryWrapper.in("approval_status_",0,1);
    Integer integer = baseMapper.selectCount(queryWrapper);
    if (integer>0){
      throw new BusinessException("人员已经在黑名单中");
    }
  }

  /**
   * 设置基本属性
   * @param userBlacklist
   */
  private void setBase(UserBlacklist userBlacklist) {
    userBlacklist.setModifyTime(new Date());
    if (null != linkappUserContextProducer.getCurrent()){
      userBlacklist.setModifyId(linkappUserContextProducer.getCurrent().getId());
    }
    //没有id就是新增,有就是编辑
    if (null == userBlacklist.getId()){
      if (null != linkappUserContextProducer.getCurrent()){
        userBlacklist.setCreatorId(linkappUserContextProducer.getCurrent().getId());
        userBlacklist.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
      }
      userBlacklist.setCreateTime(new Date());
    }
  }
}
